<template>
	<div class="sph">
		<!-- header 头部位置 -->
		<div class="header-top">
			<!-- 版心类名 居中 -->
			<div class="header-center">
				<div class="header-user">
					尚品汇欢迎您！
					<span v-if="$store.state.user.name">
						<span>{{ $store.state.user.name }}</span>
						<button @click="logout">退出登录</button>
					</span>
					<span v-else>
						请
						<router-link to="/login">登录</router-link> |
						<router-link to="/register">免费注册</router-link>
					</span>
				</div>
				<!-- 导航位置 -->
				<ul class="header-nav">
					<li><router-link to="/center">我的订单</router-link></li>
					<li><router-link to="/shopcart">我的购物车</router-link></li>
					<li>我的尚品汇</li>
					<li>尚品汇会员</li>
					<li>企业采购</li>
					<li>关注尚品汇</li>
					<li>合作招商</li>
					<li class="header-last">商家后台</li>
				</ul>
			</div>
		</div>
		<!-- header 头部搜索 log -->
		<div class="header-button">
			<!-- 版心 -->
			<div class="header-center">
				<!-- log图标 -->
				<router-link to="/home"
					><img src="./image/logo.png" alt="" class="login"
				/></router-link>
				<!-- 搜索模块 -->
				<form class="header-search" @submit.prevent="goSearch">
					<input class="header-search-inp" v-model="keyword" />
					<button class="header-search-btn">搜索</button>
				</form>
			</div>
		</div>
	</div>
</template>

<script>
export default {
	name: 'JHeader',
	methods: {
		goSearch() {
			// 获取用户输入的值
			const keyword = this.keyword
			const query = this.$route.query

			// 定义跳转Search组件
			const option = {
				name: 'Search',
				query: {
					...query,
				},
			}
			// 判断用户是否输入值   有值就带参数跳转
			if (keyword) {
				option.query.keyword = keyword
				// keyword是否有值  有值就删除掉
			} else if (option.query.keyword) {
				delete option.query.keyword
			}
			// 跳转Search
			this.$router.history.push(option)
		},
		async logout() {
			await this.$store.dispatch('user/logout')
			this.$router.replace('/login')
		},
	},
	data() {
		return {
			keyword: this.$route.query.keyword,
		}
	},
	watch: {
		// 形参是监视的那个对象
		$route($route) {
			this.keyword = $route.query.keyword
		},
	},
}
</script>

<style lang="less" scoped>
.header-top {
	background-color: #eaeaea;
	height: 30px;
}

.header-center {
	max-width: 1200px;
	height: 100%;
	margin: 0 auto;
	align-items: center;

	display: flex;
	justify-content: space-between;
}

.header-nav {
	display: flex;

	li {
		cursor: pointer;
		padding: 0 10px;
		border-right: 1px solid #b3aeae;
	}

	.header-last {
		border: none;
		padding-right: 0;
	}
}

.header-button {
	height: 100px;
}

.header-search-inp {
	width: 500px;
	padding: 5px 12px;
	border: 2px solid #ea4a36;
	border-radius: 15px;
	outline: none;
	box-sizing: border-box;
}

.header-search-btn {
	margin-left: 3px;
	width: 80px;
	height: 30px;
	background-color: #ea4a36;
	color: #fff;
	border-radius: 18px;
	border: none;
	cursor: pointer;
}
</style>
